import {
  addHospital,
  changeHospital,
  delHospital,
  delHospitals,
  getHospitals,
} from '@/services/api';
import options from '@/utils/cascader-address-options';
import { logoUrl, serverUrl } from '@/utils/tools';
import { DeleteFilled, EditFilled, PlusOutlined } from '@ant-design/icons';
import {
  ModalForm,
  PageContainer,
  ProForm,
  ProFormCascader,
  ProFormText,
  ProFormTextArea,
  ProFormUploadButton,
  ProTable,
} from '@ant-design/pro-components';

import { Button, message, Popconfirm, Space } from 'antd';
import { useRef, useState } from 'react';

function Hospital() {
  const [myForm] = ProForm.useForm();
  //选中的医院们
  const [selectedHospitals, setSelectedHospitals]: any = useState([]);
  //模态框显隐
  const [isShow, setIsShow] = useState(false);
  //新增地址搜索
  const filter = (inputValue: string, path: any) =>
    path.some(
      (option: any) =>
        (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );
  const ref: any = useRef(null);

  //当前修改的医院id
  const [changeHospitalid, setChangeHospitalid] = useState('');
  return (
    <PageContainer>
      <ProTable
        rowSelection={{
          onChange: async (arr) => {
            await setSelectedHospitals(arr);
          },
        }}
        actionRef={ref}
        rowKey="id"
        columns={[
          {
            title: '医院图片',
            hideInSearch: true,
            dataIndex: 'image',
            render(r, c) {
              if (c.image) {
                if (typeof c.image === 'string' && !c.image.startsWith('http')) {
                  c.image = [
                    {
                      uid: crypto.randomUUID(),
                      name: c.name + '.png',
                      status: 'done',
                      response: serverUrl + c.image,
                      thumbUrl: serverUrl + c.image,
                    },
                  ];
                } else if (typeof c.image === 'string' && c.image.startsWith('http')) {
                  c.image = [
                    {
                      uid: crypto.randomUUID(),
                      name: c.name.png,
                      status: 'done',
                      response: c.image,
                      thumbUrl: c.image,
                    },
                  ];
                }
              } else {
                c.image = [
                  {
                    uid: crypto.randomUUID(),
                    name: c.name.png,
                    status: 'done',
                    response: logoUrl,
                    thumbUrl: logoUrl,
                  },
                ];
              }

              return <img src={c.image[0].response} alt="医院图片" style={{ width: '100px' }} />;
            },
          },
          { title: '医院名称', ellipsis: true, copyable: true, dataIndex: 'name' },
          {
            title: '医院简介',
            ellipsis: true,
            hideInSearch: true,
            dataIndex: 'desc',
          },
          {
            title: '医院地址',

            ellipsis: true,
            hideInSearch: true,
            dataIndex: 'address',
          },
          {
            title: '联系电话',
            ellipsis: true,

            hideInSearch: true,
            dataIndex: 'phone',
          },
          {
            title: '操作',
            hideInSearch: true,
            render(r: any) {
              return (
                <Space>
                  {/* 修改 */}
                  <Button
                    type="primary"
                    shape="circle"
                    icon={<EditFilled />}
                    onClick={() => {
                      setChangeHospitalid(r.id);
                      setIsShow(true);

                      myForm.setFieldsValue(r);
                    }}
                  />
                  <Popconfirm
                    title="确认删除"
                    description="你确定删除该条医院信息吗?"
                    cancelText="取消"
                    okText="确认"
                    onConfirm={() => {
                      delHospital(r.id);
                      message.success('删除成功!');
                      ref.current.reload();
                    }}
                  >
                    <Button type="primary" shape="circle" icon={<DeleteFilled />} danger />
                  </Popconfirm>
                </Space>
              );
            },
          },
        ]}
        request={getHospitals}
        // @ts-ignore
        toolBarRender={() => (
          <>
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                setChangeHospitalid('');
                setIsShow(true);
              }}
            >
              新建
            </Button>
            <Popconfirm
              title="确认删除"
              description="你确定删除选中的医院信息吗?"
              cancelText="取消"
              okText="确认"
              onConfirm={async () => {
                await delHospitals(selectedHospitals);
                setSelectedHospitals([]);
                message.success('删除成功!');
                ref.current.clearSelected();
                ref.current.reload();
              }}
            >
              <Button
                key="button"
                icon={<DeleteFilled />}
                type="primary"
                danger
                style={{ display: selectedHospitals.length > 0 ? '' : 'none' }}
              >
                删除选中
              </Button>
            </Popconfirm>
          </>
        )}
      ></ProTable>
      <ModalForm
        form={myForm}
        title="新增医院信息"
        open={isShow}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setChangeHospitalid('');

            setIsShow(false);
          },
        }}
        submitTimeout={2000}
        // @ts-ignore
        onFinish={async (values) => {
          console.log(values);

          if (!changeHospitalid) {
            const msg = await addHospital({
              ...values,
              address: values.address?.join('/'),
            });
            // @ts-ignore
            if (msg.success) {
              setChangeHospitalid('');
              ref.current.reload();
              message.success('添加成功');
              setIsShow(false);
              return true;
            } else {
              setIsShow(false);
            }
          } else {
            const msg = await changeHospital(changeHospitalid, {
              ...values,
              address:
                typeof values.address === 'string' ? values.address : values.address?.join('/'),
            });
            // @ts-ignore
            if (msg.success) {
              setChangeHospitalid('');
              ref.current.reload();
              message.success('修改成功');
              setIsShow(false);
              return true;
            } else {
              setIsShow(false);
            }
          }
        }}
      >
        <ProFormUploadButton
          name="image"
          label="上传图片"
          max={1}
          fieldProps={{
            name: 'file',
            listType: 'picture-card',
          }}
          action={serverUrl + '/common/upload'}
        />
        <ProFormText
          required
          rules={[{ required: true, message: '这是必填项' }]}
          width="md"
          name="name"
          label="医院名称"
          tooltip="仅限已注册的公立医院"
          placeholder="请输入医院名称"
          fieldProps={{ allowClear: true, maxLength: 12, showCount: true }}
        />
        <ProFormTextArea
          required
          rules={[{ required: true, message: '这是必填项' }]}
          colProps={{ span: 24 }}
          fieldProps={{ maxLength: 3000, showCount: true, allowClear: true }}
          name="desc"
          label="描述信息"
          tooltip="从规模、服务、等级等各层面描述"
          placeholder="请输入描述信息"
        />
        <ProFormCascader
          width="md"
          name="address"
          label="请输入地址"
          tooltip="医院所在地址"
          fieldProps={{
            options: options,
            expandTrigger: 'hover',
            changeOnSelect: true,
            placeholder: '请选择或输入搜索',
            showSearch: { filter },
          }}
        />
        <ProFormText
          width="md"
          name="phone"
          label="联系电话"
          tooltip="24小时可以联系到医院的电话号"
          placeholder="请输入联系电话"
        />
      </ModalForm>
    </PageContainer>
  );
}

export default Hospital;
